from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select
from sqlalchemy.orm import selectinload
from typing import List, Dict, Any
from modules.code_genrator.models.gen_business_model import GenBusiness
from modules.code_genrator.schemas.gen_business_schema import GenBusinessCreate, GenBusinessUpdate, GenBusinessQuery


class GenBusinessService:
    @staticmethod
    async def create_gen_business(db: AsyncSession, playload: GenBusinessCreate) -> GenBusiness:
        db_gen_business = GenBusiness(**playload.model_dump())
        db.add(db_gen_business)

        await db.commit()
        await db.refresh(db_gen_business)
        return db_gen_business  

    @staticmethod
    async def get_gen_business_by_id(db: AsyncSession, gen_business_id: int) -> GenBusiness:
        result = await db.execute(
            select(GenBusiness)
            .options(selectinload(GenBusiness.columns))
            .filter(GenBusiness.id == gen_business_id)
        )
        return result.scalars().first()

    @staticmethod
    async def get_all_gen_businesses(db: AsyncSession, query: GenBusinessQuery) -> List[GenBusiness]:
        """获取所有代码生成业务"""
        stmt = select(GenBusiness).options(selectinload(GenBusiness.columns))
        if query.table_name:
            stmt = stmt.where(GenBusiness.table_name.like(f"%{query.table_name}%"))
        if query.table_comment:
            stmt = stmt.where(GenBusiness.table_comment.like(f"%{query.table_comment}%"))
        if query.start_time:
            stmt = stmt.where(GenBusiness.created_at >= query.start_time)
        if query.end_time:
            stmt = stmt.where(GenBusiness.created_at <= query.end_time)
        result = await db.execute(stmt)
        return result.scalars().all()

    @staticmethod
    async def update_gen_business(db: AsyncSession, gen_business_id: int, gen_business_data: GenBusinessUpdate) -> GenBusiness:
        db_gen_business = await GenBusinessService.get_gen_business_by_id(db, gen_business_id)
        if not db_gen_business:
            return None

        update_data = gen_business_data.model_dump(exclude_unset=True)
        for key, value in update_data.items():
            setattr(db_gen_business, key, value)
        await db.commit()
        await db.refresh(db_gen_business)
        return db_gen_business

    @staticmethod
    async def delete_gen_business(db: AsyncSession, gen_business_id: int) -> bool:
        db_gen_business = await GenBusinessService.get_gen_business_by_id(db, gen_business_id)
        if not db_gen_business:
            return False

        for column in db_gen_business.columns:
            await db.delete(column)

        await db.delete(db_gen_business)
        await db.commit()
        return True